<template>
<div>
  <div  class="mod-config" id="mod-config-id" :style="modHeight">
    <div class="div-tabs">
      <div class="div-tabs-item " :class="{'div-tabs-active':tabIs('region')}" @click="clickTabChange('region')"><span >地区角度</span></div>
      <div class="div-tabs-item" :class="{'div-tabs-active':tabIs('sale')}" @click="clickTabChange('sale')"><span >销售角度</span></div>
    </div>
    <div v-if="isAuth('regionListManage:paging')" class="div-s" id="div-s-id">
      <el-form  :model="params" :label-position="labelPosition" ref="queryFormRef" :inline="true" label-width="70px" class="queryFormed">
        <el-row v-if="tabIs('region')" class="row-s" >
          <el-col :span="6">
            <el-form-item label="所在区域" prop="areaId"  >
              <el-select v-model="areaSelectValue" placeholder="请选择区域"  @clear="clearArea" @focus="showSelectAreaDialog"  clearable>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col  :span="6">
            <el-form-item label="管理人" prop="managerId">
              <el-select v-model="params.managerId" placeholder="请选择管理人" @focus="getManagerList" @clear="clickSearch" @change="clickSearch" filterable   clearable>
                <el-option
                  v-for="item in managerOptions"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" >
            <el-form-item label="区域销售"  prop="saleId">
              <el-select v-model="params.saleId" placeholder="请选择区域销售" @focus="getSaleList" @clear="clickSearch" @change="clickSearch" filterable  clearable>
                <el-option
                  v-for="item in saleOptions"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6"  style="justify-content: flex-end">
            <el-form-item  prop="distributionFlag">
              <el-checkbox v-model="params.distributionFlag" true-label="1" false-label="0"  @change="clickSearch"  clearable>未分配区域</el-checkbox>
            </el-form-item>
            <el-form-item  prop="multiSaleFlag">
              <el-checkbox v-model="params.multiSaleFlag" true-label="1" false-label="0" @change="clickSearch"   clearable>多区域销售区域</el-checkbox>
            </el-form-item>
          </el-col>

          <el-col class="col-right" :span="6" :offset="18">
            <el-form-item class="item-all">
              <el-button class="buttonItem" size="mini" plain @click="clickReset">重 置</el-button>
              <el-button class="buttonItem" size="mini" type="primary" @click="clickSearch">搜 索</el-button>
<!--              <el-button v-if="!isUnfold" @click="turnFoldState" type="text">展开<i
                class="el-icon-arrow-down zhankai"></i></el-button>
              <el-button v-if="isUnfold" @click="turnFoldState" type="text">收起<i class="el-icon-arrow-up zhankai"></i>
              </el-button>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isAuth('regionListManage:paging')" v-show="tabIs('sale')" class="row-s" >
          <el-col :span="6">
            <el-form-item label="区域销售" prop="saleId">
              <el-select v-model="params.saleId" placeholder="请选择区域销售" @focus="getSaleList" @clear="paging" @change="clickSearch" filterable  clearable>
                <el-option
                  v-for="item in saleOptions"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col class="col-right" :span="6" :offset="12">
            <el-form-item class="item-all">
              <el-button class="buttonItem" size="mini" plain @click="clickReset">重 置</el-button>
              <el-button class="buttonItem" size="mini" type="primary" @click="clickSearch">搜 索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="div-e" id="div-e-id">
      <div class="div-inquire" id="div-inquire-id">
        <div class="in-t">
          <div class="in-ts"></div>
          <h3 >区域名单管理</h3>
        </div>
        <div  class="div-button">
          <el-button v-if="tabIs('region')"  size="mini" type="primary" @click="changeRegionType">{{ isRegionListFuc() ? '切换树形模式' :  '切换列表模式' }}</el-button>
          <el-button v-if="isAuth('regionListManage:export')" size="mini" type="primary" icon="el-icon-upload2" @click="clickExport">数据导出</el-button>
          <el-button v-if="tabIs('sale') && isAuth('regionListManage:allocate')" size="mini" type="primary" icon="" @click="showSaleDialogVisible" :disabled="allocateForm.saleIdList.length < 1">分配</el-button>
        </div>
      </div>
      <el-table
        v-show="tabIs('region') && !isRegionListFuc()"
        ref="regionMultipleTable"
        :data="tableData"
        :max-height="table.tableHeight"
        :header-cell-style="{background:'#F5F7FA'}"
        :tree-props="{children: 'children'}"
        row-key="id"
        style="width: 100%"
        v-loading="dataListLoading"
        @row-click="ClickRowHandle"
        fit>
<!--        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="城市"
          width="200"
          prop="cityName"
          align="center">
        </el-table-column>
        <el-table-column
          prop="cityManagerName"
          label="管理人(城市)"
          width="200"
          align="center">
        </el-table-column>
        <el-table-column
          prop="cityManagerEffectiveDays"
          label="有效时间(城市)"
          width="200"
          align="center">
        </el-table-column>-->
        <el-table-column
          prop="name"
          label="区域"
          align="center">
        </el-table-column>
        <el-table-column
          prop="managerName"
          label="管理人"

          align="center">
        </el-table-column>
        <el-table-column
          prop="effectiveDays"
          label="有效时间(地区)"

          align="center">
        </el-table-column>
        <el-table-column
          prop="areaSaleNames"
          label="区域销售"
          align="center">
        </el-table-column>
        <el-table-column
          label="操作"
          width="300"
          align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.distributionAble === 1 && isAuth('regionListManage:allocate') && scope.row.typeId === 3" type="text" size="mini" class="btn-text-normal" @click="showRegionDialogVisible(scope.row)"  >分配</el-button>
            <span v-else-if="scope.row.typeId === 2" type="text" class="btn-text-normal"  ></span>
            <span v-else type="text" class="btn-text-normal"  >非该区域负责人，无分配权限</span>
            <el-button v-if="scope.row.distributionAble === 1 && isAuth('regionListManage:cancelAllocate') && scope.row.typeId === 3 && scope.row.managerName" type="text" size="mini" class="btn-text-danger" @click="tackBackRegionalReq(scope.row)"  >取消分配</el-button>
            <span v-else-if="scope.row.typeId === 2" type="text" class="btn-text-normal"  ></span>

          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-show="tabIs('sale')"
        ref="saleMultipleTable"
        :data="tableData"
        :max-height="table.tableHeight"
        :header-cell-style="{background:'#F5F7FA'}"
        style="width: 100%"
        v-loading="dataListLoading"
        @selection-change="saleHandleSelectionChange"
        fit>
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="姓名"
          width="200"
          prop="nickName"
          align="center">
        </el-table-column>
        <el-table-column
          prop="saleRegion"
          label="销售区域"
          align="center">
          <template slot-scope="scope">
            <div v-for="(region,index) in scope.row.saleRegionList" style="margin-left: 10px;display: inline-block"><el-tag style="cursor: pointer" @click="clickRegionTag(scope,region,index)">{{ `${region.cityName}-${region.areaName}:${region.dayAmount}` }}</el-tag></div>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-show="tabIs('region') && isRegionListFuc()"
        :data="tableData"
        :max-height="table.tableHeight"
        :header-cell-style="{background:'#F5F7FA'}"
        style="width: 100%"
        border
        v-loading="dataListLoading"
        fit>
        <el-table-column
          label="地区"
          width="220"
          prop="name"
          align="center">
        <template slot-scope="slot">
          <div>
            <span>{{slot.row.name}}</span>
            <div>
              <div><CircleTag v-if="slot.row.managerName" :name-str="slot.row.managerName" style="margin-right: 5px" :circle-color="slot.row.managerColorCode"></CircleTag>{{`(${slot.row.dealCustomerAmount ? slot.row.dealCustomerAmount : 0};${slot.row.unDealCustomerAmount ? slot.row.unDealCustomerAmount : 0})`}}</div>
            </div>
          </div>
        </template>
        </el-table-column>
        <el-table-column
          label="负责人"
          prop="managerName"
          align="center">
          <template slot-scope="slot">
            <el-row>
              <el-col v-for="area in slot.row.children" :span="4">
                <div style="display: flex;align-items: center">
                  <el-button type="text" style="margin-right: 6px;color: #606266" @click="showChangeManagerDialog(area,slot.row)">{{area.name}}</el-button>
                  <el-tooltip v-if="area.managerName || area.areaSaleNames" placement="top">
                    <span slot="content">{{area.managerName ? `负责人：${area.managerName}  ` : ''}}{{area.areaSaleNames ? `销售：${area.areaSaleNames}` : ''}}</span>
                      <circle-tag v-if="area.managerName" :name-str="area.managerName" style="margin-right: 3px;cursor: pointer" :circle-color="area.managerColorCode" @click.native="showChangeManagerDialog(area,slot.row)"></circle-tag>
                  </el-tooltip>
                  <circle-tag v-if="area.areaSaleNames" :name-str="area.areaSaleNames" circle-size="small" style="cursor: pointer" @click.native="showChangeManagerDialog(area,slot.row)"></circle-tag>
                </div>

              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="tabIs('sale')"
        @size-change="changePageSize"
        @current-change="turnToPage"
        :current-page="queryInfo.pageIndex"
        :page-sizes="[5, 10, 20, 50, 100, 200]"
        :page-size="queryInfo.pageSize "
        layout="total, prev, pager, next, sizes, jumper"
        :total="totalPage"
        id="div-e-paging-id">
      </el-pagination>
    </div>
  </div>
  <el-dialog
    title=""
    :visible.sync="saleDialogVisible"
    width="30%">
    <h3 slot="title">分配</h3>
    <div>
      <el-form :model="allocateForm" :rules="allocateFormRules" ref="saleAllocateFormRefs" label-width="100px">
        <el-form-item label="城市" prop="cityId">
          <el-select v-model="allocateForm.cityId" @focus="getCityList" @change="saleChangeCityOption" filterable style="width: 79%">
            <el-option
              v-for="item in cityOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">

            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="areaId">
          <el-select v-model="allocateForm.areaId" @focus="getAreaList" style="width: 79%" filterable>
            <el-option
              v-for="item in areaOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
          <el-row>
            <el-form-item label="有效时间">
            <el-col :span="12">
              <el-date-picker
              v-model="allocateForm.endTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择有效时间"
              style="width: 100%"
              :disabled="allocateForm.alwaysFlag === 1">
            </el-date-picker>
            </el-col>
              <el-col :span="6" :offset="1">
                <el-checkbox v-model="allocateForm.alwaysFlag" :true-label="1" :false-label="0" @change="changeAlwaysFlag">是否永久</el-checkbox>
              </el-col>
            </el-form-item>
          </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="saleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allocateSaleToRegion">确 定</el-button>
  </span>
  </el-dialog>

  <el-dialog
    title=""
    :visible.sync="regionDialogVisible"
    width="30%">
    <h3 slot="title">分配</h3>
    <div>
      <el-form :model="allocateForm" :rules="allocateFormRules" ref="regionAllocateForm" label-width="100px">
        <el-row>
          <el-col :span="22">
            <el-form-item label="区域销售" prop="saleIdList">
              <el-select v-model="allocateForm.saleIdList" style="width: 100%" multiple collapse-tags clearable>
                <el-option
                  v-for="item in saleOptions"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="有效时间">
            <el-col :span="12">
              <el-date-picker
                v-model="allocateForm.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择有效时间"
                style="width: 100%"
                :disabled="allocateForm.alwaysFlag === 1">
              </el-date-picker>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-checkbox v-model="allocateForm.alwaysFlag" :true-label="1" :false-label="0" @change="changeAlwaysFlag">是否永久</el-checkbox>
            </el-col>
          </el-form-item>
        </el-row>
<!--          <el-form-item label="有效时间" >
            <el-row>
          <el-col :span="12" >
              <el-date-picker
                v-model="allocateForm.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择有效时间"
                :disabled="allocateForm.alwaysFlag === 1">
              </el-date-picker>
          </el-col>
          <el-col :span="6" >
            <el-checkbox v-model="allocateForm.alwaysFlag" :true-label="1" :false-label="0">是否永久</el-checkbox>
          </el-col>
            </el-row>

          </el-form-item>-->


      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="regionDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allocateRegionToSale">确 定</el-button>
  </span>
  </el-dialog>

  <el-dialog
    title=""
    :visible.sync="selectAreaDialogVisible"
    top="20vh"
    width="35%">
      <h3 slot="title">
        选择地区
      </h3>
    <div style="border: 1px solid #DDDDDD;border-radius: 2px;height: 30vh;overflow: auto;margin: 0 40px 28px 40px;padding: 13px 20px">
      <el-tree :data="areaTreeData" :props="areaTreeProps" @node-click="areaHandleNodeClick" ></el-tree>
    </div>
    <span style="display: flex;justify-content: center;">
        <el-button @click="selectAreaDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSelectAreaSearch">确 认</el-button>
      </span>
  </el-dialog>

  <el-dialog
    title=""
    :visible.sync="changeAreaManagerDialogVisible"
    width="30%"
    @closed="initManagerAllocateForm">
    <h3 slot="title">{{managerAllocateForm.areaName}}</h3>
    <el-form :model="managerAllocateForm" ref="managerAllocateFormRefs"  label-width="120px">
      <el-form-item label="区域管理人" prop="managerId"  :rules="{ required: true, message: '请选择区域管理人', trigger: 'change' }">
<!--      <el-form-item label="区域管理人"   required>-->
        <el-select style="width: 100%" v-model="managerAllocateForm.managerId" placeholder="请选择管理人" @focus="getManagerList"   filterable>
          <el-option
            v-for="item in managerOptions"
            :key="item.id"
            :label="item.nickName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="管理人有效日期" prop="managerEndTime"  :rules="{ required:managerAllocateForm.managerAlwaysFlag === 0,  message: '请选择管理人有效时间', trigger: 'blur' }">
<!--      <el-form-item label="管理人有效日期"   >-->
        <el-date-picker
          v-model="managerAllocateForm.managerEndTime"
          style="width: 50%"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择管理人结束日期"
        :disabled="managerAllocateForm.managerAlwaysFlag === 1">
        </el-date-picker>
        <el-checkbox style="margin-left: 20%" v-model="managerAllocateForm.managerAlwaysFlag" :true-label="1" :false-label="0" @change="changeManagerAlwaysFlag">是否永久</el-checkbox>
      </el-form-item>
<!--      <el-form-item label="区域销售" prop="saleIdList" :rules="{ required:true, message: '请选择区域销售', trigger: 'change' }">-->
      <el-form-item label="区域销售" >
        <el-select style="width: 100%" v-model="managerAllocateForm.saleIdList" placeholder="请选择区域销售" @focus="getSaleList" multiple filterable>
          <el-option
            v-for="item in saleOptions"
            :key="item.id"
            :label="item.nickName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售有效日期" prop="saleEndTime"  :rules="{ required: managerAllocateForm.saleAlwaysFlag === 0, message: '请选择销售有效日期', trigger: 'blur' }">
<!--      <el-form-item label="销售有效日期"   >-->
        <el-date-picker
          v-model="managerAllocateForm.saleEndTime"
          style="width: 50%"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择销售结束日期"
          :disabled="managerAllocateForm.saleAlwaysFlag === 1">
        </el-date-picker>
        <el-checkbox style="margin-left: 20%" v-model="managerAllocateForm.saleAlwaysFlag" :true-label="1" :false-label="0" @change="changeSaleAlwaysFlag">是否永久</el-checkbox>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="changeAreaManagerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allocateManagerAndSale">确 认</el-button>
  </span>
  </el-dialog>

  <el-dialog
    title=""
    :visible.sync="allotRegionDialogVisible"
    width="30%">
    <h3 slot="title">分配</h3>
    <div>
      <el-form :model="allotForm" :rules="allotFormRules" ref="allotFormRef" label-width="100px">
        <el-row>
          <el-col :span="22">
            <el-form-item label="地区" prop="regionName">
              <el-input v-model="allotForm.regionName" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="区域销售" prop="regionName">
              <el-select v-model="allotForm.saleIdList" style="width: 100%" multiple collapse-tags clearable>
                <el-option
                  v-for="item in saleOptions"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="有效时间">
            <el-col :span="12">
              <el-date-picker
                v-model="allotForm.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择有效时间"
                style="width: 100%"
                :disabled="allotForm.alwaysFlag === 1">
              </el-date-picker>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-checkbox v-model="allotForm.alwaysFlag" :true-label="1" :false-label="0" @change="(val)=>{val===1?allotForm.endTime='': ''}">是否永久</el-checkbox>
            </el-col>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="allotRegionDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRegionToSale">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
import BasePaging from '../../common/BasePaging'
import ElTreeSelect from '../../../components/treeSelect/index.vue'
import { isAuth, twoArrIntersection } from '../../../utils'
import {
  allocateRegionToSale,
  allocateSaleToRegion, getRegionalDetailByIdReq,
  regionalListManageExport, tackBackRegional
} from '../../../api/customer/regionalListManage'
import {allocateRegion, getAreaTree, getRegionList, getRegionTree} from '../../../api/customer/region'
import {getUserList} from '../../../api/user'
import CircleTag from './Component/CircleTag'

export default {
  name: 'region-list-manage',
  components: {CircleTag, ElTreeSelect},
  extends: BasePaging,
  created () {
    this.adjustTableHeight()
    this.getAreaTree()
    this.getManagerList()
    this.getSaleList()
    if (this.isAuth('regionListManage:paging')) { this.paging() }
  },
  data () {
    return {
      params: {
        'areaId': '',
        'saleId': '',
        'managerId': '',
        'distributionFlag': 0,
        'multiSaleFlag': 0
      },
      labelPosition: 'right',
      isRegionList: true,
      regionDialogVisible: false,
      saleDialogVisible: false,
      selectAreaDialogVisible: false,
      changeAreaManagerDialogVisible: false,
      // tabs切换FLag region,sale
      tabsFlag: 'region',
      dataListLoading: false,
      areaSelectValue: '',
      tableData: [],
      cityOptions: [],
      regionList: [],
      areaOptions: [],
      saleOptions: [],
      areaTreeData: [],
      areaTreeProps: {
        children: 'children',
        label: 'name'
      },
      managerOptions: [],
      allocateForm: {
        cityId: '',
        areaId: '',
        saleId: '',
        saleIdList: [],
        endTime: '',
        typeId: 1,
        alwaysFlag: 1
      },
      managerAllocateForm: {
        typeId: 3,
        areaName: '',
        cityId: '',
        areaId: '',
        managerId: '',
        managerEndTime: '',
        managerAlwaysFlag: 1,
        saleIdList: [],
        saleEndTime: '',
        saleAlwaysFlag: 1
      },
      allocateFormRules: {
        cityId: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        areaId: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        saleIdList: [
          { required: true, message: '请选择区域销售', trigger: 'change' }
        ]
      },
      allotFormRules: {

      },
      allotForm: {
        regionName: '',
        cityId: '',
        areaId: '',
        saleId: '',
        saleIdList: [],
        endTime: '',
        typeId: 2,
        alwaysFlag: 1
      },
      allotRegionDialogVisible: false
    }
  },
  methods: {
    twoArrIntersection: twoArrIntersection,
    isAuth (auth) {
      return isAuth(auth)
    },
    isRegionListFuc () {
      return this.isRegionList
    },
    paging () {
      let conditions = {}
      let data = {}
      let url = ''
      this.dataListLoading = true
      if (this.tabIs('region')) {
        url = '/ent/area/user/tree/list'
        data['saleId'] = this.params.saleId
        data['areaId'] = this.params.areaId
        data['managerId'] = this.params.managerId
        data['distributionFlag'] = this.params.distributionFlag
        data['multiSaleFlag'] = this.params.multiSaleFlag
      } else {
        url = '/ent/user/area/paging'
        conditions.saleId = this.params.saleId
        data['conditions'] = conditions
        data['inOrder'] = ''
        data['orderBy'] = ''
        data['pageNum'] = this.queryInfo.pageIndex
        data['pageSize'] = this.queryInfo.pageSize
      }
      this.$http({
        url: this.$http.adornUrl(url),
        method: 'post',
        data: this.$http.adornData(data)
      }).then(({data}) => {
        if (data.code === 0) {
          if (this.tabsFlag === 'sale') {
            this.saleAreaTransformer(data.data.records)
            this.tableData = data.data.records
            this.totalPage = data.data.total
          } else {
            this.tableData = data.data
          }
        } else {
          this.$message.error(data.msg)
        }
      }).finally(() => { this.dataListLoading = false })
    },
    // 初始化表单
    initAllocateForm () {
      this.allocateForm.cityId = ''
      this.allocateForm.areaId = ''
      this.allocateForm.saleId = ''
      this.allocateForm.saleIdList = []
      this.allocateForm.endTime = ''
      this.allocateForm.typeId = 1
      this.queryInfo.pageSize = 20
      this.queryInfo.pageIndex = 1
    },
    // 初始化搜索参数
    initParams () {
      this.params.areaId = ''
      this.params.saleId = ''
      this.params.managerId = ''
      this.params.distributionFlag = 0
      this.params.multiSaleFlag = 0
      this.areaSelectValue = ''
    },
    // 获取销售列表
    getSaleList () {
      getUserList({
        'nickName': '',
        'name': '',
        'areaManagerFlag': 0
      }, (data) => {
        this.saleOptions = data.data
      })
    },
    // 销售列表中的销售区域转换
    saleAreaTransformer (data = []) {
      // console.log('dataBefor', data)
      data.forEach((saler) => {
        saler.saleRegion = ''
        saler.saleRegionList = []
        if (saler.saleList !== null) {
          saler.saleList.forEach((city) => {
            if (city.areaList !== null) {
              city.areaList.forEach((area, index) => {
                // saler.saleRegion += city.cityName + '-' + area.areaName + ':' + area.dayAmount
                let regionObj = { cityName: city.cityName, areaName: area.areaName, areaId: area.id, cityId: city.id, dayAmount: area.dayAmount }
                saler.saleRegionList.push(regionObj)
                if (index === 0) {
                  saler.saleRegion += city.cityName + '-' + area.areaName + ':' + area.dayAmount
                } else {
                  saler.saleRegion += '、' + area.areaName + ':' + area.dayAmount
                }
                if (index === city.areaList.length - 1) {
                  saler.saleRegion += '；'
                }
              })
            } else {
              city.areaList = []
            }
          })
        } else {
          saler.salelist = []
        }
      })
    },
    getRegionalTreeReq () {
      getRegionTree({'actionId': 2}, (data) => { this.regionList = data.data })
    },
    // 获取城市列表
    getCityList () {
      getRegionList(
        {
          'name': '',
          'parentId': '',
          'typeId': 2,
          'actionId': 1
        },
        (data) => {
          this.cityOptions = data.data
        }
      )
    },
    // 获取地区列表
    getAreaList () {
      getRegionList(
        {
          'name': '',
          'parentId': this.allocateForm.cityId,
          'typeId': 3,
          'actionId': 1
        },
        (data) => { this.areaOptions = data.data }
      )
    },
    // 获取管理人列表
    getManagerList () {
      getUserList({
        'nickName': '',
        'name': '',
        'areaManagerFlag': 1
      }, (data) => { this.managerOptions = data.data })
    },
    getAreaTree () {
      getAreaTree({'actionId': 2}, (data) => { this.areaTreeData = data.data })
    },
    // 区域角度
    regionHandleSelectionChange (selection) {
    },
    showRegionDialogVisible (row) {
      this.allocateForm.cityId = row.parentId
      this.allocateForm.areaId = row.id
      this.allocateForm.typeId = 1
      this.allocateForm.saleIdList = row.areaSaleNames ? row.areaSaleList.map(item => item.id) : null
      this.getSaleList()
      this.regionDialogVisible = true
    },
    allocateRegionToSale () {
      this.$refs.regionAllocateForm.validate((valida) => {
        if (valida) {
          allocateRegionToSale({
            'cityId': this.allocateForm.cityId,
            'areaId': this.allocateForm.areaId,
            'userIdList': this.allocateForm.saleIdList,
            'typeId': 2,
            'endTime': this.allocateForm.endTime,
            'alwaysFlag': this.allocateForm.alwaysFlag
          }, () => { this.paging() })
          this.regionDialogVisible = false
        } else {
          return false
        }
      })
    },
    // 销售角度
    saleHandleSelectionChange (selection) {
      // eslint-disable-next-line no-unused-vars
      this.allocateForm.saleIdList = selection.map(item => item.id)
    },
    showSaleDialogVisible () {
      this.saleDialogVisible = true
    },
    allocateSaleToRegion () {
      this.$refs.saleAllocateFormRefs.validate((valida) => {
        if (valida) {
          allocateSaleToRegion({
            'cityId': this.allocateForm.cityId,
            'areaId': this.allocateForm.areaId,
            'userIdList': this.allocateForm.saleIdList,
            'typeId': 2,
            'endTime': this.allocateForm.endTime,
            'alwaysFlag': this.allocateForm.alwaysFlag
          }, () => { this.paging() })
          this.saleDialogVisible = false
        } else {
          return false
        }
      })
    },
    // 调节table高度
    getOtherHeight (val) {
      return 36
    },
    // 判断当前Tab是啥
    tabIs (tabFlag) {
      return this.tabsFlag === tabFlag
    },
    // 标签点击事件
    clickTabChange (tab) {
      this.tabsFlag = tab
      this.tableData = []
      this.initAllocateForm()
      this.initParams()
      this.paging()
    },
    // 查询条件重置
    clickReset () {
      this.$refs['queryFormRef'].resetFields()
      this.areaSelectValue = ''
      this.paging()
    },
    // 清空搜索条件
    clearSearch () {
      this.paging()
    },
    clickSearch () {
      this.queryInfo.pageIndex = 1
      this.paging()
    },
    clearArea () {
      this.params.areaId = ''
      this.areaSelectValue = ''
      this.clickSearch()
    },
    showSelectAreaDialog () {
      this.getAreaTree()
      this.selectAreaDialogVisible = true
    },
    areaHandleNodeClick (nodeObj, node) {
      this.areaSelectValue = node.data.name
      this.params.areaId = node.data.id
    },
    clickExport () {
      let data = {...this.params}
      let fileName = '区域名单管理（地区角度）'
      if (this.tabsFlag === 'region') {
        data.typeId = 1
      } else {
        data.typeId = 2
        fileName = '区域名单管理（销售角度）'
      }
      regionalListManageExport(
        data,
        fileName
      )
    },
    changeAlwaysFlag (val) {
      if (val === 1) {
        this.allocateForm.endTime = ''
      }
    },
    clickSelectAreaSearch () {
      this.clickSearch()
      this.selectAreaDialogVisible = false
    },
    // 点击表格行，展开行
    ClickRowHandle (row, clo, event) {
      let tableRefs = this.$refs.regionMultipleTable
      tableRefs.toggleRowExpansion(row)
    },
    // 分配弹出框城市地区
    saleChangeCityOption () {
      this.allocateForm.areaId = ''
    },
    tackBackRegionalReq (row) {
      console.log('row', row)
      this.$confirm(`确定删除 “${row.name}”的区域销售吗？`, '提示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        type: 'warning'
      }).then(() => {
        let formData = {}
        formData['cityId'] = row.parentId
        formData['areaIdList'] = [row.id]
        // typeId 1区域管理 2区域销售
        formData['typeId'] = 2
        tackBackRegional(formData, () => { this.paging() }, () => {})
      })
    },
    initManagerAllocateForm () {
      this.managerAllocateForm.areaName = null
      this.managerAllocateForm.cityId = null
      this.managerAllocateForm.areaId = null
      this.managerAllocateForm.managerId = null
      this.managerAllocateForm.managerEndTime = null
      this.managerAllocateForm.managerAlwaysFlag = 1
      this.managerAllocateForm.saleIdList = []
      this.managerAllocateForm.saleEndTime = null
      this.managerAllocateForm.saleAlwaysFlag = 1
    },
    changeRegionType () {
      this.isRegionList = !this.isRegionList
      this.paging()
    },
    showChangeManagerDialog (area, row) {
      this.getManagerList()
      this.getSaleList()
      // console.log('area', area)
      // console.log('row', row)
      // console.log('row', area)
      this.managerAllocateForm['areaName'] = area.name
      this.managerAllocateForm['cityId'] = area.parentId
      this.managerAllocateForm['areaId'] = area.id
      this.managerAllocateForm['saleIdList'] = area.areaSaleList ? area.areaSaleList.map(item => item.id) : []
      if (area.managerName) {
        this.managerAllocateForm['managerId'] = area.managerId
        if (area.managerAlwaysFlag) {
          this.managerAllocateForm['managerEndTime'] = ''
        } else {
          this.managerAllocateForm['managerAlwaysFlag'] = area.managerAlwaysFlag
          this.managerAllocateForm['managerEndTime'] = area.managerEndTime
        }
      }

      if (area.areaSaleNames) {
        if (area.areaSaleList[0].alwaysFlag) {
          // this.managerAllocateForm['saleAlwaysFlag'] = area.areaSaleList[0].saleAlwaysFlag
          this.managerAllocateForm['saleEndTime'] = ''
        } else {
          this.managerAllocateForm['saleAlwaysFlag'] = area.areaSaleList[0].alwaysFlag
          this.managerAllocateForm['saleEndTime'] = area.areaSaleList[0].endTime
        }
      }
/*      this.managerAllocateForm['managerEndTime'] = !area.managerAlwaysFlag ? area.managerEndTime : ''
      this.managerAllocateForm['saleEndTime'] = (!area.managerAlwaysFlag && area.areaSaleList) ? area.areaSaleList[0].endTime : null
      this.managerAllocateForm['managerAlwaysFlag'] = area.managerAlwaysFlag
      this.managerAllocateForm['saleAlwaysFlag'] = area.areaSaleList[0].saleAlwaysFlag */
      this.changeAreaManagerDialogVisible = true
    },
    changeManagerAlwaysFlag (val) {
      if (val === 1) {
        this.managerAllocateForm.managerEndTime = ''
      }
    },
    changeSaleAlwaysFlag (val) {
      if (val === 1) {
        this.managerAllocateForm.saleEndTime = ''
      }
    },
    allocateManagerAndSale () {
      let dataForm = {}
      dataForm['cityId'] = this.managerAllocateForm.cityId
      dataForm['areaId'] = this.managerAllocateForm.areaId
      // dataForm['areaIdList'] = this.managerAllocateForm.areaIdList
      // dataForm['userIdList'] = this.managerAllocateForm.userIdList
      dataForm['typeId'] = 3
      dataForm['managerId'] = this.managerAllocateForm.managerId
      dataForm['managerAlwaysFlag'] = this.managerAllocateForm.managerAlwaysFlag
      dataForm['managerEndTime'] = this.managerAllocateForm.managerEndTime || null
      dataForm['saleIdList'] = this.managerAllocateForm.saleIdList
      dataForm['saleAlwaysFlag'] = this.managerAllocateForm.saleAlwaysFlag
      dataForm['saleEndTime'] = this.managerAllocateForm.saleEndTime || null
      this.$refs.managerAllocateFormRefs.validate((valid) => {
        if (valid) {
          allocateRegion(dataForm, () => {
            this.paging()
            this.changeAreaManagerDialogVisible = false
          },
            () => {
              this.paging()
              this.changeAreaManagerDialogVisible = false
            })
        } else {
         // this.$message.warning('请检查信息是否填写完整！')
          return false
        }
      })
    },
    showAllotRegionDialog () {
      this.allotRegionDialogVisible = true
    },
    clickRegionTag (scope, region, index) {
      if (region.areaId) {
        getRegionalDetailByIdReq(region.areaId, ({data}) => {
          let {parentId, areaSaleList, id, name} = data
          let selectedSaleIdList = areaSaleList.map(sale => sale.id)
          this.allotForm.cityId = parentId
          this.allotForm.areaId = id
          this.allotForm.saleIdList = this.twoArrIntersection(selectedSaleIdList, this.allSaleIdList)
          this.allotForm.regionName = `${region.cityName}-${name}`
          this.allotForm.endTime = areaSaleList[0].endTime
          this.allotForm.alwaysFlag = areaSaleList[0].alwaysFlag
          this.showAllotRegionDialog()
        })
      }
    },
    allotRegionToSale () {
      allocateRegionToSale({
        'cityId': this.allotForm.cityId,
        'areaId': this.allotForm.areaId,
        'userIdList': this.allotForm.saleIdList,
        'typeId': 2,
        'endTime': this.allotForm.endTime,
        'alwaysFlag': this.allotForm.alwaysFlag
      }, () => {
        this.paging()
        this.allotRegionDialogVisible = false
      })
    }

  },
  computed: {
    allSaleIdList () {
      return this.saleOptions.map(sale => sale.id)
    }
  }

}
</script>


